package com.util.excel.toproperties;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class FileProperties
{

	private String fileName;

	private Map<Object, Properties> map;

	private static FileProperties fileProperties;

	public static FileProperties getInstence(String fileName)
	{
		if (null == fileProperties)
		{
			fileProperties = new FileProperties(fileName);
		}
		return fileProperties;
	}

	private FileProperties(String fileName)
	{
		if (null == fileName)
			throw new IllegalArgumentException("fileName  must not null");
		this.fileName = fileName;
		map = new HashMap<Object, Properties>();

		try
		{
			File file = new File(fileName);
			if (file.exists())
			{
				ObjectInputStream fin = new ObjectInputStream(new FileInputStream(file));
				Properties[] properties = (Properties[]) fin.readObject();

				for (Properties p : properties)
				{
					map.put(p.get(ReadFaiceExcel.FACEBOOK_NAME), p);
				}

			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public Properties get(Object key)
	{
		return map.get(key);
	}

	public Properties[] get()
	{
		if (map.size() <= 0)
		{
			return null;
		}

		Set<Object> set = map.keySet();
		Properties[] p = new Properties[map.size()];

		int i = 0;

		for (Object o : set)
		{
			p[i] = map.get(o);
			i++;
		}
		return p;
	}

	public void put(Properties pro)
	{
		map.put(pro.getProperty(ReadFaiceExcel.FACEBOOK_NAME), pro);
	}

	public void save()
	{
		ObjectOutputStream out = null;
		try
		{
			File f = new File(fileName);
			if (f.exists())
			{
				f.delete();
			}

			f.createNewFile();

			out = new ObjectOutputStream(new FileOutputStream(f));
			Properties[] p = get();
			if (null == p)
			{
				return;
			}
			out.writeObject(p);
			out.flush();
		}
		catch (Exception e)
		{
		}
		finally
		{
			close(out);
		}
	}

	private void close(Closeable stream)
	{
		if (null != stream)
		{
			try
			{
				stream.close();
			}
			catch (IOException e)
			{
			}
			stream = null;
		}

	}
}